import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import autobind from "autobind-decorator";
import Icon from "../../components/Icon/";

// submodule
import "./index.less";

import {
    setTitle,
    setRight
} from "../../utils/dingtalk.js";
import { formatDate } from "../../utils/common.js";
import { get } from "../../utils/db";

import AnnualList from "./annualList.jsx"
import BirthdayList from "./birthdayList.jsx"

import urlParams from "../../utils/urlParams";

// actions
import { fetchMemorialDayInfo } from "../../actions/memorialDay/index.js";

// 将store注入组件的props
const mapStateToProps = state => ({});
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
    //区分绑定到props的action与传递的props
    actions: bindActionCreators(
        {
            fetchMemorialDayInfo,
            dispatch
        },
        dispatch
    )
});

const MemorialType = {
    'birthday': '生日关怀',
    'anniversary': '入职周年纪念'
}

@connect(mapStateToProps, mapDispatchToProps)
export default class MemorialDay extends Component {
    static propTypes = {
        location: PropTypes.object,
        actions: PropTypes.shape({
            fetchMemorialDayInfo: PropTypes.func.isRequired
        }).isRequired,
    };

    constructor(props) {
        super(props);
        let date = new Date();
        if (this.props.location.query.date) {
            date = new Date(this.props.location.query.date);
        }
        const y = date.getFullYear(), m = date.getMonth();

        const isFromShare = !!urlParams.getUrlSearchParam("userIdBirth");

        this.state = {
            type: this.props.location.query.type || 'birthday',
            currentDate: new Date(y, m, 10),
            date: new Date(y, m, 10),
            memorial_data_count: 0,
            isFromShare
        };
        setRight({
            show: false
        })
        setTitle({
            title: MemorialType[this.props.location.query.type]
        });
    }

    componentDidMount() {
        this.fetchMemorialDayInfo()
    }

    @autobind
    changeMonth(type) {
        const thisDate = this.state.date;
        const nextMonth = type === "previous" ? thisDate.getMonth() - 1 : thisDate.getMonth() + 1;
        thisDate.setMonth(nextMonth);
        this.setState({
            date: thisDate
        }, ()=> {
            this.fetchMemorialDayInfo();
        })
        this.props.router.replace(`/memorialDay?type=${this.state.type}&date=${formatDate(thisDate)}`);
    }

    @autobind
    fetchMemorialDayInfo() {
        const type = this.state.type;
        const scheduleTypes = type === "birthday" ? [1] : [2];
        const userId = urlParams.getUrlSearchParam("userIdBirth");
        const data = {
            scheduleTypes,
            scheduleMonth: this.state.date.toJSON()
        }
        if (userId) {
            Object.assign(data, { userId });
        }
        this.props.actions.fetchMemorialDayInfo(data).then(res => {
            if (res.success) {
                
                const memorial_data = type === "birthday" ? res.result.birthdayEmpList : res.result.annualEmpList;
                const memorial_data_count = type === "birthday" ? res.result.birthdayTotalNum : res.result.annualTotalNum;
                this.setState({
                    memorial_data,
                    memorial_data_count,
                    notHaveBirthdayEmpTotalNum: res.result.notHaveBirthdayEmpTotalNum,
                    notHaveAnnualEmpTotalNum: res.result.notHaveAnnualEmpTotalNum,
                    notHaveAnnualEmpUserIds: res.result.notHaveAnnualEmpUserIds,
                    notHaveBirthdayEmpUserIds: res.result.notHaveBirthdayEmpUserIds
                })
            }
        })
    }

    @autobind
    share() {
        const month = this.state.date.getMonth() + 1;
        const icon = this.state.type === "birthday" ? 
            "https://gw.alicdn.com/tfs/TB18Q1Dc_vI8KJjSspjXXcgjXXa-88-88.png" :
            "https://gw.alicdn.com/tfs/TB1xIUWaOqAXuNjy1XdXXaYcVXa-88-88.png"
        const content = this.state.type === "birthday" ? 
            `记得为他们送上祝福哦！` :
            `感谢他们的努力付出，让我们一起送上祝福吧！`
        const title = this.state.type === "birthday" ? 
            `${month}月有${this.state.memorial_data_count}名员工过生日` :
            `${month}月有${this.state.memorial_data_count}名同事入职周年庆`

        const userId = get("userId");
        const url = `${urlParams.replaceSearch({userIdBirth:userId})}#/memorialDay?type=${this.state.type}`;
        if(dd.compareVersion("3.5.6",dd.version)){
            dd.biz.util.share({
                "style": 0,
                "type": 3,
                "buttonName": "确定",
                "custom": {
                    "dd": {
                        "title": title,                    
                        "content": content,
                        "image": icon,
                        "url": url,
                    }
                },
                "onlyShare": true,
                "destChannelStyle": "dd"
            })
        }else{
            dd.biz.util.share({
                "type":1,
                "title": title,                    
                "content": content,
                "image": icon,
                "url": url,
            });
        }
    }

    render() {
        const type = this.state.type;
        const thisDate = this.state.date;
        const memorial_data_count = +this.state.memorial_data_count;
        const yearMonth = `${thisDate.getFullYear()}年${thisDate.getMonth() + 1}月`;
        const showManage = !this.state.isFromShare
        let monthText = yearMonth;
        if (thisDate.toDateString() === this.state.currentDate.toDateString()) {
            monthText = `本月（${yearMonth}）`
        }

        const banner_url = type === "birthday" ?
            'https://gw.alicdn.com/tfs/TB1ZdwkbLDH8KJjy1XcXXcpdXXa-698-128.png' :
            'https://gw.alicdn.com/tfs/TB1gHWGcZLJ8KJjy0FnXXcFDpXa-750-128.png'
        return (
            <div className={`memorial_day_container ${type}`}>
                <div className="date-range">
                    {showManage &&
                        <span className={`left ${false && 'disabled'}`} onClick={() => {
                            this.changeMonth('previous')
                        }}>
                            <Icon type="left" />
                        </span>
                    }

                    <span className={`center${!showManage ? ' fullWidth' : ''}`}>
                        {monthText}
                    </span>

                    {showManage &&
                        <span className={`right ${false && 'disabled'}`} onClick={() => {
                            this.changeMonth('next')
                        }}>
                            <Icon type="right" />
                        </span>
                    }

                </div>
                <div className="banner">
                    <img src={banner_url} alt="birthday_banner"/>
                </div>
                <div className="memorial-body-container">
                    <div>
                    {type === 'anniversary' ?
                        <AnnualList
                            showManage={showManage}
                            data={this.state.memorial_data}
                            notHaveAnnualEmpTotalNum={this.state.notHaveAnnualEmpTotalNum} 
                            notHaveAnnualEmpUserIds={this.state.notHaveAnnualEmpUserIds}
                            count={memorial_data_count} 
                            month={thisDate.getMonth() + 1} /> : 
                        <BirthdayList
                            showManage={showManage}
                            data={this.state.memorial_data}
                            notHaveBirthdayEmpTotalNum={this.state.notHaveBirthdayEmpTotalNum} 
                            notHaveBirthdayEmpUserIds={this.state.notHaveBirthdayEmpUserIds}
                            count={memorial_data_count} 
                            month={thisDate.getMonth() + 1} />}
                    {
                        showManage && memorial_data_count !== 0 &&
                        <div className="bottom_btn_container">
                            <div className="bottom_btn" onClick={this.share}>
                                告诉同事
                            </div>
                        </div>
                    }
                    </div>
                </div>

            </div>
        );
    }
}